#include <sys/types.h>        
#include <sys/socket.h>        
#include <netinet/in.h>        
#include <netdb.h>        
#include <stdio.h>   
#include <unistd.h>   
#include <stdlib.h>   
#include <string.h>       
#include <fcntl.h>       
#define SMTP_SERVER   "smtp.163.com"
#define SMTP_CMD_EHLO "EHLO %s\r\n"
#define SMTP_CMD_AUTH "AUTH LOGIN\r\n"
#define SMTP_CMD_FROM "MAIL FROM:<%s>\r\n"
#define SMTP_CMD_RCPT "RCPT TO:<%s>\r\n"
#define SMTP_CMD_DATA "DATA\r\n"
#define SMTP_CMD_QUIT "QUIT\r\n"
#define SMTP_CMD_LINE "\r\n"
#define SMTP_CMD_END  "\r\n.\r\n"
#define SMTP_ADDR_LEN 128
#define MAIL_ADDR_LEN 128
#define USERNAME_MAX_LEN 128
#define PASSWORD_MAX_LEN 128
#define SUBJECT_LEN   128

#define SMTP_TIME_OUT 3

class CMailer
{
public:
    CMailer();
    CMailer(const char*);
    ~CMailer();
    int set_user(const char* in_szUserName,
                 const char* in_szPassWord);

    int set_smtp(const char* in_szSmtp);

    int send_mail(const char* in_szAddr,
                  const char* in_szSubject,
                  const char* in_szContent,
                  size_t in_nLen);
private:
    //  socket 操作函数
    int connect_server();
    int set_socket_timeout();
    int readn();
    int writen(const char*, size_t);
    int writen(const char*);

    // smtp操作函数
    int login();
    int set_from(const char*);
    int set_rcpt(const char*);
    int init_mail();

    int set_mail_header(const char*);
    int send_subject(const char*);
    int send_content(const char*, size_t);

    int quit_smtp();

    //base64编码函数
    int Base64Encode(char*, char* ,int);
    int get_user_name(const char*, char*);

    //  成员变量
    int  m_nSockFd;
    char m_szBuf[BUFSIZ + 1];
    //smtp.xx.com
    char m_szSmtp[SMTP_ADDR_LEN];
    //lyccode@163.com
    char m_szFromAddr[MAIL_ADDR_LEN];
    //lyccode
    char m_szUserName[USERNAME_MAX_LEN];
    //password
    char m_szPassWord[PASSWORD_MAX_LEN];
    //username as base64
    char m_szUSRB64[USERNAME_MAX_LEN];
    //password as base64
    char m_szPWDB64[PASSWORD_MAX_LEN];
    struct sockaddr_in m_server;
    struct hostent *hp;
};

